#!/usr/bin/env python
# coding=utf-8
# provide DTO types for this project

import re
__author__ = 'vavava'

# TrackItem.track_status
TRACING  = 0
RETRYING = 0
FAILED   = 0

class TrackItem(object):
    """ Tracking summary """
    def __init__(self,ID=-1,Name="",TrackTime=None,
                 Description="",Location="",Shipment_ID=-1,
                 Created=None ):
        self.Name        = Name
        self.TrackTime   = TrackTime
        self.Description = Description
        self.Location    = Location
        self.Created     = Created
        #self.Modified    = Modified
        self.ID          = ID
        self.Shipment_ID = Shipment_ID

        # status
        self.last_tracking_time=None
        self.last_update_time=None
        self.track_status=TRACING

    @staticmethod
    def GetInstance(db_data):
        item = TrackItem()
        item.ID          = db_data[0]
        item.Name        = db_data[1]
        item.TrackTime   = db_data[2]
        item.Description = db_data[3]
        item.Location    = db_data[4]
        item.Shipment_ID = db_data[5]
        item.Created     = db_data[6]
        #item.Modified    = db_data[]
        return item

    def __hash__(self):
        """
        define for dic key
        hash by Name,TrackTime,Description,Location
        """
        key = "%s%s%s%s"%(self.Name,self.TrackTime,self.Description,self.Location)
        return key.__hash__()

    def __eq__(self, other):
        """ define for dic key """
        return self.Name == other.Name\
                and self.TrackTime   == other.TrackTime\
                and self.Description == other.Description\
                and self.Location    == other.Location

    @staticmethod
    def parse(item_name="",text=None):
        """ parse from html fragment
            return TrackItem
         """
        import datetime
        try:
            if text:
                reg_str=r'<td[^>]*>(?P<content>.*?)(<span[^<]*?</span>)*</td>'
                reg = re.compile(reg_str,re.X)
                match = reg.findall(text)
                if match:
                    if 'No events found' in match[0][0]:
                        return None
                    t1= datetime.datetime.strptime(match[0][0], "%d/%m/%y %H:%M")
                    return TrackItem(
                        Name=item_name,
                        TrackTime=t1,
                        Description=match[1][0],
                        Location=match[2][0],
                        Created=datetime.datetime.now()
                    )
        except Exception as e:
            print(e)
            return None
        return None

if __name__ == "__main__":
    strkk = r'<td class="date">01/10/12 01:47</td><td>In Transit</td><td>DERRIMUT VIC </td>'
    strkk = r' <td colspan="3">No events found</td>'
    ti = TrackItem.parse("name",strkk)
    print(ti)
    pass
